package com.guli.auth.service.impl;
/*
 * @Author 罗
 * @date 2020/10/19 - 8:35 上午
 */

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.guli.auth.config.WeiBoSecretProperties;
import com.guli.auth.feign.MemberServiceFeignClient;
import com.guli.auth.service.LoginService;
import com.guli.common.to.MemberTo;
import com.guli.auth.vo.UserVo;
import com.guli.auth.vo.WeiBoEntityVo;
import com.guli.common.pojo.vo.StatusCodeEnum;
import com.guli.common.utils.HttpUtils;
import com.guli.common.utils.R;
import com.guli.mall.serviceBase.globalException.MallException;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.io.IOException;

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {


    @Resource
    MemberServiceFeignClient memberServiceFeignClient;


    public static final TypeReference<MemberTo> TYPE_REFERENCE_MEMBER_TO = new TypeReference<MemberTo>() {
    };

    @Override
    public MemberTo loginByUserNameAndPassword(UserVo userVo) {

        R login = memberServiceFeignClient.login(userVo);

        if (login.getCode().equals(StatusCodeEnum.SUCCESS.getCode())) {

            return JSON.parseObject(login.getDefaultData(), MemberTo.class);

        }
        throw new MallException(login);
    }


    @Override
    public MemberTo getAccessTokenByToken(String code) throws IOException {

        CloseableHttpResponse httpResponse = HttpUtils.post(WeiBoSecretProperties.UrlForGetAccessToken + code);

        if (httpResponse.getStatusLine().getStatusCode() != 200) {
            throw new MallException(StatusCodeEnum.WEI_BO_LOGIN_EXCEPTION);
        }

        HttpEntity responseEntity = httpResponse.getEntity();

        String jsonEntity = EntityUtils.toString(responseEntity);

        WeiBoEntityVo weiBoEntityVo = JSON.parseObject(jsonEntity, WeiBoEntityVo.class);

        /**
         * 检查用户是否为第一次登陆，如果是第一次登陆，那么要将该用户添加到数据库
         * */
        MemberTo memberTo = new MemberTo();

        memberTo.setWeiBoUid(weiBoEntityVo.getUid());

        memberTo.setExpiresIn((long) weiBoEntityVo.getExpires_in());

        memberTo.setWeiBoAccessToken(weiBoEntityVo.getAccess_token());

        R r = memberServiceFeignClient.loginFromWeiBoUid(memberTo);

        return r.getData(TYPE_REFERENCE_MEMBER_TO);


    }
}
